import React from 'react';
import {gameService} from "./services/GameService";
import Token from "./Token";
import PlayerBoard from "./PlayerBoard";

export default class Players extends React.Component {
    state = {};
	endTurn = () => {
			let player = gameService.getPlayerFromId(gameService.currentPlayer);
			if(player.money < -300 && player.bankruptTurns == 2){

					gameService.bankrupt();
					this.setState({selected: 1});
					gameService.currentPlayer = 1;
			}else{
					gameService.endTurn();
			}
	}
		bankrupt = false;
		bankruptUI = () =>{
				if(this.bankrupt){

					gameService.bankrupt();
					this.setState({selected: 1});
					gameService.currentPlayer = 1;
				}else{
						this.bankrupt = true;
				}

		}
    render() {
        const selected = this.state.selected;
        const players = this.props.game.players.sort((p1, p2) => {
            return gameService.scorePlayerForSorting(p1) - gameService.scorePlayerForSorting(p2);
        });
        return (<div className="player-list">
			{ (gameService.currentPlayer != 1) ? (
					<div>
							<button onClick={this.endTurn}>end TURN !</button>
							<button onClick={this.bankruptUI}>BANKRUPT !!!</button>
					</div>
			) : ("")
			}
            <h3>Players</h3>
            <div className="player-tabs">
                {players.map(p => <div key={p.id}
                                       onClick={() => this.setState({selected: p.id})}
                                       className={"player "}>
                    <Token token={p.token} selected={p.id === selected}/>
                    {p.name}
                </div>)}
            </div>
            <PlayerBoard player={this.state.selected} game={this.props.game}/>
        </div>)
    }
}
